package com.usac.arqui1.grupo2.proyecto1.app;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.Application;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

public class utilGlobals extends Application {

	private BluetoothDevice d;
	private BluetoothSocket socket;
	
	/**
	 * 
	 * @return un dispositivo bluetooth
	 */
	public BluetoothDevice getD() {
		return d;
	}
	
	/**
	 * Almacena el dispositivo bluetooth encontrado.
	 * @param d Dispositivo Bluetooth
	 */
	public void setD(BluetoothDevice d) {
		this.d = d;
	}
	
	/**
	 * Metodo que conecta el dispositivo existente, y crea el socket de comunicación
	 */
	public void conectaSocket() {
		Method m = null;
		try {
			m = d.getClass().getMethod("createRfcommSocket",
					new Class[] { int.class });
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			socket = (BluetoothSocket) m.invoke(d, 1);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//Conecta
		try {
			socket.connect();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Este metodo envía cualquier cadena que reciba a traves del Socket de comunicacion bluetooth.
	 * @param msg String que recibe para ser enviado.
	 */
	public void sendMessage(String msg) {
		OutputStream outStream;
		try {
			outStream = socket.getOutputStream();
			byte[] byteString = (msg + " ").getBytes();
			byteString[byteString.length - 1] = 0;
			outStream.write(byteString);
			socket.close();
		} catch (IOException e) {
			Log.d("BLUETOOTH_COMMS", e.getMessage());
		}
	}

}